(function ($) {
    "use strict";

    var URL = {
        servreq: {
            getServReqs: "/rest/servreq/getServReqs?{0}",
            getServReqsCount: "/rest/servreq/getServReqsCount?status={0}"
        },
        patient: {
            checkIcNo: "/rest/patient/checkIcNo?patient_Id={1}&icNo={0}",
            createPatient: "/rest/patient/createPatient?{0}",
            getProcessedPatients: "/rest/patient/getProcessedPatients?{0}",
            getProcessedPatientsCount: "/rest/patient/getProcessedPatientsCount?like={0}",
            getPatient: "/rest/patient/getPatient?patient_Id={0}",
            getPatients: "/rest/patient/getPatients?{0}",
            getPatientsCount: "/rest/patient/getPatientsCount?status={0}&like={1}",
            setInitial: "/rest/patient/setInitial?patient_Id={0}",
            setNeedDiag: "/rest/servreq/setNeedDiag?",
            setNeedSolution: "/rest/servreq/setNeedSolution?servReq_Id={0}&user_Id={1}",
            setNew: "/rest/patient/setNew?patient_Id={0}",
            setNeedOpe: "/rest/servreq/setNeedOpe?",
            setFinish4Diag:"/rest/servreq/setFinish4Diag?",
            setFinish4OpeSolu:"/rest/servreq/setFinish4OpeSolu?",
            setNoOpeNeeded: "/rest/servreq/setNoOpeNeeded?",
            setRetByMedAdmin: "/rest/servreq/setRetByMedAdmin?",
            setRetNON: "/rest/servreq/setRetNON?",
            setRetBySpecia: "/rest/servreq/setRetBySpecia?",
            updatePatient1: "/rest/patient/updatePatient1?{0}",
            updatePatient2: "/rest/patient/updatePatient2?{0}",
            sharePatient:"/rest/chat/createChatMessageSharingPatient?"
        },        
        user: {
            getUsers: "/rest/user/getUsers?userRole={0}&like={1}&pageNo={2}&pageSize={3}"
        },
        diseaseType: {
            getDiseaseType: "/rest/diseasetype/getDiseaseTypeList?"
        }
    };

    app.controller("DiagnosisCtrl", DiagnosisCtrl);

    function DiagnosisCtrl($compile, $modal, $rootScope, $scope, $translate, toaster, RESTService, $filter, $stateParams) {
        // init
        var modelInstance, rowCountInstance;
        $scope.servReq_Id = $stateParams.servReq_Id;
        $rootScope.rowCount = 0;
        $scope.like = '';
        $scope.current = $scope.$state.current.url;

        $scope.open = function (attrs, data, handler) {
            $scope.modelInstance = $modal.open(angular.extend({
                backdrop: "static",
                controller: "ModalInstanceCtrl",
                resolve: {
                    items: function () {
                        return [Object(data)];
                    }
                },
                scope: $scope
            }, attrs));

            if (undefined !== handler && "function" === typeof $scope[handler]) {
                $scope[handler]();
            }

        };

        $scope.flag_needOpe = false;
        $scope.flag_setNoOpeNeeded = false;
        $scope.flag_setNew = false;
        $scope.flag_imageDiag = false;
        $scope.flag_opeSche = false;
        $scope.setNeedOpe = function (){
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flat_opeSche = false;
            $scope.flag_needOpe = true;
        };
        $scope.setNoOpeNeeded = function (){
            $scope.flag_needOpe = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = false;
            $scope.flag_setNoOpeNeeded = true;
        };
        $scope.setNew = function (){
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = false;
            $scope.flag_setNew = true;
        };
        $scope.imageDiag = function (){
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_opeSche = false;
            $scope.flag_imageDiag = true;
        };
        $scope.opeSche = function (){
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = true;
        };

        // get no. of patients
        (rowCountInstance = function (handler) {
            var url = ("/filter" === $scope.$state.current.url || "/diagnosis" === $scope.$state.current.url)
                ? URL.servreq.getServReqsCount : URL.patient.getPatientsCount;
            RESTService.getResponse(url.format($scope.filterStatus, $scope.like)).then(
                function (response) {
                    $rootScope.rowCount = ~~response[0].count;
                    handler && handler();
                });
            RESTService.getResponse("/rest/servreq/getServReqs?status=all&like=" + $scope.like)
                .then(function (response) {
                    $scope.servReqs = response;
                });
        })();

        // get patients with pagination
        $scope.dtOptions = {
            aaSorting: [],
            bFilter: false,
            bLengthChange: false,
            bSort: false,
            bStateSave: false,
            oLanguage: {
                sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
            },
            processing: true,
            serverSide: true,
            sAjaxDataProp: "data",
            ajax: function (data, callback) {
                // prepare query variables
                console.log(12345678, data);
                var params = {
                    status: $scope.filterStatus,
                    like: $scope.like,
                    pageNo: data.start / data.length + 1,
                    pageSize: data.length
                };
                var sort = [], i;

                if (0 !== data.order.length) {
                    for (i in data.order) {
                        if (data.order.hasOwnProperty(i)) {
                            sort.push({
                                property: data.columns[data.order[i].column].data,
                                direction: data.order[i].dir.toUpperCase()
                            });
                        }
                    }

                    if (0 !== sort.length) {
                        params.sort = angular.toJson(sort);
                    }
                }

                if (3 <= data.search.value.length) {
                    params.filter = data.search.value;
                }
                // transmit to server
                var url = "/patcase" === $scope.$state.current.url ? URL.patient.getPatients : URL.servreq.getServReqs;
                RESTService.getResponse(url.format($.param(params))).then(
                    function (response) {
                        $scope.$parent.patients = [];
                        angular.forEach(response, function (item) {
                            item.No = $scope.$parent.patients.length + (params.pageNo * params.pageSize) - 9;
                            $scope.$parent.patients.push(item);
                        });
                        callback({
                            aaData: [],
                            draw: data.draw,
                            recordsTotal: $rootScope.rowCount,
                            recordsFiltered: $rootScope.rowCount
                        });
                        console.log('--------------请求已发');
                        $scope.dtInstance.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                    });
            },
            fnCreatedRow: function (row) {
                $compile(row)($scope);
            },
            fnInitComplete: function () {
                $scope.$parent.dtInstance = this.fnSetFilteringDelay();
            }
        };

        $scope.diagConsts = [
            {key: "none", type: "diag", name: $filter('translate')('diagconsts.none.name')},
            {key: "mild", type: "diag", name: $filter('translate')('diagconsts.mild.name')},
            {key: "serious", type: "diag", name: $filter('translate')('diagconsts.serious.name')}
        ];

        RESTService.getResponse(URL.user.getUsers.format("Specialist", "", 1, 1000)).then(
            function (response) {
                $scope.specialists = response;
            });

        $scope.onSetSelection = function ($event, status, servReq_Id, input) {

            var params;

            switch (status) {
                case "RetByMedAdmin":   //    "/rest/servreq/setRetByMedAdmin?servReq_Id={0}&{1}"
                case "RetNON":
                    // input = $.param(angular.extend({
                    //     desc: ""
                    // }, input));
                    params = {
                        servReq_Id : servReq_Id,
                        desc : input.desc
                    }
                    break;
                case "RetBySpecia":    //   "/rest/servreq/setRetBySpecia?servReq_Id={0}&{1}" 退回给区域医生
                    params = {
                        servReq_Id : servReq_Id,
                        diag_Desc : input.diag_Desc
                    };
                    break;
                case "NeedDiag":   //   "/rest/servreq/setNeedDiag?servReq_Id={0}&user_Id={1}"  初筛-是否需要手术
                    if (1 > input || undefined === _.findWhere($scope.specialists, {userId: ~~input})) {
                        return toaster.pop("error", $translate.instant("business.patcase.send_for_diagnosis_specialist_error"));
                    }
                    params = {
                        servReq_Id : servReq_Id,
                        user_Id : input.user_Id
                    }
                    break;
                default:
            }

            $($event.currentTarget).button("loading");

            console.log('========================================servReq_Id:',servReq_Id, 'input:',input);

            // RESTService.getResponse(URL.patient["set" + status].format(servReq_Id, input)).then(
            //     function () {
            //
            //         rowCountInstance(function () {
            //             $scope.dtInstance.DataTable().ajax.reload();
            //             $scope.modelInstance && $scope.modelInstance.close();
            //             modelInstance = undefined; // clear instances when done
            //         });
            //     });
            // var urll = RESTService.getResponse(URL.patient["set" + status], params);
            // console.log(urll);
            RESTService.postResponse(URL.patient["set" + status], params).then(
                function () {
                    rowCountInstance(function () {
                        $scope.dtInstance.DataTable().ajax.reload();
                        $scope.modelInstance && $scope.modelInstance.close();
                        modelInstance = undefined; // clear instances when done
                    });
                });
        };

        $scope.diseaseType = [];
        RESTService.getResponse(URL.diseaseType.getDiseaseType).then(function (response) {
            $scope.diseaseType = response;
        });

        $scope.onSetStatus = function ($event, status, patientId, input) {
            // setFinish4OpeSolu:"/rest/servreq/setFinish4OpeSolu?servReq_Id={0}&{1}
            var params;
            switch (status) {
                case "NeedOpe":
                case "Finish4Diag":
                    params = {
                        servReq_Id : patientId,
                        diseaseType : input.diseaseType,
                        diag_Desc : input.diag_Desc
                    };
                    // input = $.param(angular.extend({
                    //     diseaseType: "",
                    //     diag_Desc: ""
                    // }, input));
                    // console.log('testtttttttttttttttt:',params);
                    break;
                case "NoOpeNeeded":
                    params = {
                        servReq_Id : patientId,
                        diag_Desc : input.diag_Desc
                    }
                    // input = $.param(angular.extend({
                    //     diag_Desc: ""
                    // }, input));
                    break;
                // case "Finish4Diag":
                //     params = {
                //         servReq_Id : patientId,
                //         diseaseType: input.diseaseType,
                //         diag_Desc: input.diag_Desc
                //     };
                    // input = $.param(angular.extend({
                    //     diseaseType: "",
                    //     diag_Desc: ""
                    // }, input));
                    break;
                case "Finish4OpeSolu":
                    params = {
                        servReq_Id : patientId,
                        opeSolu_Desc : input.opeSolu_Desc
                    }
                    // input = $.param(angular.extend({
                    //     opeSolu_Desc: ""
                    // }, input));
                    break;

                default:
            }

            $($event.currentTarget).button("loading");
            // RESTService.getResponse(URL.patient["set" + status].format(patientId, input),true).then(
            //     function (data) {
            //         if (data.code == 0){
            //             rowCountInstance(function () {
            //                 $scope.dtInstance.DataTable().ajax.reload();
            //                 $scope.modelInstance && $scope.modelInstance.close();
            //             });
            //         }
            //         $($event.currentTarget).button("reset");
            //     });
            RESTService.postResponse(URL.patient["set" + status], params, true).then(
                function (data) {
                    console.log('data:',data);
                    if (data.code == 0){
                        rowCountInstance(function () {
                            $scope.dtInstance.DataTable().ajax.reload();
                            $scope.modelInstance && $scope.modelInstance.close();
                        });
                    }
                    $($event.currentTarget).button("reset");
                });
        };

        // get list of friends
        RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
            $scope.friendList = [];
            angular.forEach(response, function (value) {
                if(value.userId>0){
                    this.push({
                        userId: value.userId,
                        userName: value.userName,
                        pic: value.pic
                    });
                }
            }, $scope.friendList);
        });

        // share case
        $scope.sharePatient = function(a, b){
            var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
            var params = {
                patient_Id:patient_Id
                ,friendId:b
            }
            console.log(params);
            RESTService.postResponse(URL.patient.sharePatient, params).then(
                function (suc) {
                    console.log(suc);
                });
        }
    }

    // app.controller("UserDetailCtrl", ["$scope", "RESTService",
    //     function ($scope, RESTService) {
    //         $scope.user = angular.extend({}, $scope.selected.item);
    //
    //         $scope.activityList = [];
    //
    //         if ($scope.user._doctor == null) {
    //             $scope.user._doctor = {
    //                 userId: '',
    //                 doctQuali_Id: '',
    //                 hosp_Id: '',
    //                 dept_Id: '',
    //                 doctor_Intro: '',
    //                 fee_Recommend: 0,
    //                 fee_Diag: 0,
    //                 fee_Solution: 0,
    //                 cost_Surgery: 0,
    //                 fee_Surgery: 0
    //             }
    //         }
    //
    //         $scope.page = {
    //             totalItems: 0,
    //             currentPage: 1,
    //             currentItems: 0,
    //             maxSize: 5,				//max size of pagination
    //             itemsPerPage: 10
    //         }
    //
    //         $scope.getActivityList = function () {
    //             var params = {
    //                 userId: $scope.user.userId,
    //                 pageNo: 1,
    //                 pageSize: 10
    //             };
    //             RESTService.getResponse("/rest/useractivity/getUserActivityList?" + $.param(params)).then(function (response) {
    //                 $scope.activityList = response;
    //             });
    //         }
    //
    //         $scope.getActivityList();
    //
    //         function User(item) {
    //             var user = {
    //                 userId: item.userId,
    //                 realName: item.realName,
    //                 mobile_Phone: item.mobile_Phone,
    //                 email: item.email,
    //                 icCardFile: item.icCardFile,
    //                 icNo: item.icNo,
    //                 gender: item.gender,
    //                 race_Id: item.race_Id,
    //                 age: item.age,
    //                 location_Country: item.location_Country,
    //                 location_Province: item.location_Province,
    //                 location_City: item.location_City,
    //                 location_County: item.location_County,
    //                 location_Town: item.location_Town,
    //                 location_Address: item.location_Address,
    //                 marriage: item.marriage,
    //                 telephone: item.telephone,
    //                 emerg_Contact: item.emerg_Contact,
    //                 emerg_Contact_Mobile: item.emerg_Contact_Mobile,
    //                 photo_File: item.photo_File
    //             };
    //             return user;
    //         };
    //         function Doctor(item) {
    //             var doctor = {
    //                 userId: item.userId,
    //                 doctQuali_Id: item.doctQuali_Id,
    //                 hosp_Id: item.hosp_Id,
    //                 dept_Id: item.dept_Id,
    //                 doctor_Intro: item.doctor_Intro,
    //                 fee_Recommend: item.fee_Recommend,
    //                 fee_Diag: item.fee_Diag,
    //                 fee_Solution: item.fee_Solution,
    //                 cost_Surgery: item.cost_Surgery,
    //                 fee_Surgery: item.fee_Surgery
    //             };
    //             return doctor;
    //         };
    //
    //         //获取好友列表
    //         $scope.isFriend = false;
    //         $scope.userId = $scope.user.userId;
    //         RESTService.getResponse("/rest/chat/getChats?").then(function(response){
    //             $scope.userIdList = [];
    //             angular.forEach(response,function(value){
    //                 $scope.userIdList.push(value.userId);
    //             });
    //             if(!Array.value){
    //                 if($.inArray($scope.userId,$scope.userIdList) < 0){
    //                     $scope.isFriend = true;
    //                 }
    //             }
    //             return $scope.isFriend;
    //         });
    //
    //         //加好友
    //         $scope.addFriends = function(userId){
    //             $scope.friendId = userId;
    //             var url = '/rest/chat/createChatMessageAddingFriend?';
    //             RESTService.postResponse(url,{friendId:$scope.friendId})
    //                 .then(function(response){
    //                     console.log(JSON.stringify(response),'kkkkkkkkkkk');
    //                 });
    //             $scope.cancel();
    //         };
    //     }]);
})(jQuery);

